<!DOCTYPE html>
<html lang="en">
  <head>
    <title>
        Java-Se-集合 - rulerLwx Blog
      </title>
        <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport"
      content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no, minimal-ui">
    <meta name="renderer" content="webkit">
    <meta http-equiv="Cache-Control" content="no-transform" />
    <meta http-equiv="Cache-Control" content="no-siteapp" />
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black">
    <meta name="format-detection" content="telephone=no,email=no,adress=no">
    
    <meta name="theme-color" content="#000000" />
    
    <meta http-equiv="window-target" content="_top" />
    
    
    <meta name="description" content="Collection 集合体系、家族 常用的集合类： java.util.Collection |- Set |- HashSet |- LinkedHashSet |- TreeSet |- EnumSet |- List |- ArrayList |- LinkedList |- Vector |- Queue |- PriorityQueue |- Deque |- ArrayDeque |- LinkedList java.util.Map |- HashMap |- Hashtable |- LinkedHashMap |- TreeMap |- EnumMap |- Properties 关于迭代 问：在迭代过程中能" />
    <meta name="generator" content="Hugo 0.73.0 with theme pure" />
    <title>Java-Se-集合 - rulerLwx Blog</title>
    
    
    <link rel="stylesheet" href="https://rulerLwx.gitee.io/css/style.min.c4bc7071f132c964c2116bca53b392933f377e5ca7b7051ed245187c621a2d3e.css">
    
    <link rel="stylesheet" href="https://cdn.staticfile.org/highlight.js/9.15.10/styles/github.min.css" async>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/tocbot/4.4.2/tocbot.css" async>
    <meta property="og:title" content="Java-Se-集合" />
<meta property="og:description" content="Collection 集合体系、家族 常用的集合类： java.util.Collection |- Set |- HashSet |- LinkedHashSet |- TreeSet |- EnumSet |- List |- ArrayList |- LinkedList |- Vector |- Queue |- PriorityQueue |- Deque |- ArrayDeque |- LinkedList java.util.Map |- HashMap |- Hashtable |- LinkedHashMap |- TreeMap |- EnumMap |- Properties 关于迭代 问：在迭代过程中能" />
<meta property="og:type" content="article" />
<meta property="og:url" content="https://rulerLwx.gitee.io/2020/07/java-se-%E9%9B%86%E5%90%88/" />
<meta property="article:published_time" content="2020-07-01T18:58:47+08:00" />
<meta property="article:modified_time" content="2020-07-01T18:58:47+08:00" />
<meta itemprop="name" content="Java-Se-集合">
<meta itemprop="description" content="Collection 集合体系、家族 常用的集合类： java.util.Collection |- Set |- HashSet |- LinkedHashSet |- TreeSet |- EnumSet |- List |- ArrayList |- LinkedList |- Vector |- Queue |- PriorityQueue |- Deque |- ArrayDeque |- LinkedList java.util.Map |- HashMap |- Hashtable |- LinkedHashMap |- TreeMap |- EnumMap |- Properties 关于迭代 问：在迭代过程中能">
<meta itemprop="datePublished" content="2020-07-01T18:58:47&#43;08:00" />
<meta itemprop="dateModified" content="2020-07-01T18:58:47&#43;08:00" />
<meta itemprop="wordCount" content="4943">



<meta itemprop="keywords" content="," /><meta name="twitter:card" content="summary"/>
<meta name="twitter:title" content="Java-Se-集合"/>
<meta name="twitter:description" content="Collection 集合体系、家族 常用的集合类： java.util.Collection |- Set |- HashSet |- LinkedHashSet |- TreeSet |- EnumSet |- List |- ArrayList |- LinkedList |- Vector |- Queue |- PriorityQueue |- Deque |- ArrayDeque |- LinkedList java.util.Map |- HashMap |- Hashtable |- LinkedHashMap |- TreeMap |- EnumMap |- Properties 关于迭代 问：在迭代过程中能"/>

    <!--[if lte IE 9]>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/classlist/1.1.20170427/classList.min.js"></script>
      <![endif]-->

    <!--[if lt IE 9]>
        <script src="https://cdn.jsdelivr.net/npm/html5shiv@3.7.3/dist/html5shiv.min.js"></script>
        <script src="https://cdn.jsdelivr.net/npm/respond.js@1.4.2/dest/respond.min.js"></script>
      <![endif]-->
  </head>

  
  

  <body class="main-center theme-black" itemscope itemtype="http://schema.org/WebPage"><header class="header" itemscope itemtype="http://schema.org/WPHeader">
    <div class="slimContent">
      <div class="navbar-header">
        <div class="profile-block text-center">
          <a id="avatar" href="https://gitee.com/rulerLwx" target="_blank">
            <img class="img-circle img-rotate" src="https://rulerLwx.gitee.io/avatar.png" width="200" height="200">
          </a>
          <h2 id="name" class="hidden-xs hidden-sm">rulerLwx</h2>
          <h3 id="title" class="hidden-xs hidden-sm hidden-md">thinking...</h3>
          <small id="location" class="text-muted hidden-xs hidden-sm"><i class="icon icon-map-marker"></i>Guangzhou, China</small>
        </div><div class="search" id="search-form-wrap">
    <form class="search-form sidebar-form">
        <div class="input-group">
            <input type="text" class="search-form-input form-control" placeholder="Search" />
            <span class="input-group-btn">
                <button type="submit" class="search-form-submit btn btn-flat" onclick="return false;"><i
                        class="icon icon-search"></i></button>
            </span>
        </div>
        <div class="ins-search">
            <div class="ins-search-mask"></div>
            <div class="ins-search-container">
                <div class="ins-input-wrapper">
                    <input type="text" class="ins-search-input" placeholder="Type something..."
                        x-webkit-speech />
                    <button type="button" class="close ins-close ins-selectable" data-dismiss="modal"
                        aria-label="Close"><span aria-hidden="true">×</span></button>
                </div>
                <div class="ins-section-wrapper">
                    <div class="ins-section-container"></div>
                </div>
            </div>
        </div>
    </form>
</div>
        <button class="navbar-toggle collapsed" type="button" data-toggle="collapse" data-target="#main-navbar" aria-controls="main-navbar" aria-expanded="false">
          <span class="sr-only">Toggle navigation</span>
          <span class="icon-bar"></span>
          <span class="icon-bar"></span>
          <span class="icon-bar"></span>
        </button>
      </div>
      <nav id="main-navbar" class="collapse navbar-collapse" itemscope itemtype="http://schema.org/SiteNavigationElement" role="navigation">
        <ul class="nav navbar-nav main-nav">
            <li class="menu-item menu-item-home">
                <a href="/">
                    <i class="icon icon-home-fill"></i>
                  <span class="menu-title">Home</span>
                </a>
            </li>
            <li class="menu-item menu-item-archives">
                <a href="/posts/">
                    <i class="icon icon-archives-fill"></i>
                  <span class="menu-title">Archives</span>
                </a>
            </li>
            <li class="menu-item menu-item-categories">
                <a href="/categories/">
                    <i class="icon icon-folder"></i>
                  <span class="menu-title">Categories</span>
                </a>
            </li>
            <li class="menu-item menu-item-tags">
                <a href="/tags/">
                    <i class="icon icon-tags"></i>
                  <span class="menu-title">Tags</span>
                </a>
            </li>
            <li class="menu-item menu-item-about">
                <a href="/about/">
                    <i class="icon icon-cup-fill"></i>
                  <span class="menu-title">About</span>
                </a>
            </li>
        </ul>
      </nav>
    </div>
  </header>

<aside class="sidebar" itemscope itemtype="http://schema.org/WPSideBar">
  <div class="slimContent">
    
      <div class="widget">
    <h3 class="widget-title">Board</h3>
    <div class="widget-body">
        <div id="board">
            <div class="content">enjoy~
            </div>
        </div>
    </div>
</div>

      <div class="widget">
    <h3 class="widget-title"> Categories</h3>
    <div class="widget-body">
        <ul class="category-list">
            <li class="category-list-item"><a href="https://rulerLwx.gitee.io/categories/java-framework/" class="category-list-link">java-framework</a><span class="category-list-count">38</span></li>
            <li class="category-list-item"><a href="https://rulerLwx.gitee.io/categories/java-front-end/" class="category-list-link">java-front-end</a><span class="category-list-count">11</span></li>
            <li class="category-list-item"><a href="https://rulerLwx.gitee.io/categories/java-se/" class="category-list-link">java-se</a><span class="category-list-count">21</span></li>
            <li class="category-list-item"><a href="https://rulerLwx.gitee.io/categories/java-senior/" class="category-list-link">java-senior</a><span class="category-list-count">4</span></li>
            <li class="category-list-item"><a href="https://rulerLwx.gitee.io/categories/linux/" class="category-list-link">linux</a><span class="category-list-count">13</span></li>
            <li class="category-list-item"><a href="https://rulerLwx.gitee.io/categories/tools/" class="category-list-link">tools</a><span class="category-list-count">1</span></li>
            <li class="category-list-item"><a href="https://rulerLwx.gitee.io/categories/%E6%8A%80%E6%9C%AF%E6%9D%82%E7%83%A9/" class="category-list-link">技术杂烩</a><span class="category-list-count">4</span></li>
            <li class="category-list-item"><a href="https://rulerLwx.gitee.io/categories/%E6%95%B0%E6%8D%AE%E5%BA%93/" class="category-list-link">数据库</a><span class="category-list-count">15</span></li>
        </ul>
    </div>
</div>
      <div class="widget">
    <h3 class="widget-title"> Tags</h3>
    <div class="widget-body">
        <ul class="tag-list">
            
            
            <li class="tag-list-item"><a href="https://rulerLwx.gitee.io/tags/jvm/" class="tag-list-link">jvm</a><span
                    class="tag-list-count">1</span></li>
            
            
            <li class="tag-list-item"><a href="https://rulerLwx.gitee.io/tags/%E5%A4%9A%E7%BA%BF%E7%A8%8B/" class="tag-list-link">多线程</a><span
                    class="tag-list-count">2</span></li>
            
            
            <li class="tag-list-item"><a href="https://rulerLwx.gitee.io/tags/%E7%BD%91%E7%BB%9C%E7%BC%96%E7%A8%8B/" class="tag-list-link">网络编程</a><span
                    class="tag-list-count">3</span></li>
            
        </ul>

    </div>
</div>
      
<div class="widget">
    <h3 class="widget-title">Recent Posts</h3>
    <div class="widget-body">
        <ul class="recent-post-list list-unstyled no-thumbnail">
            <li>
                <div class="item-inner">
                    <p class="item-title">
                        <a href="https://rulerLwx.gitee.io/2020/07/%E8%87%AA%E5%B7%B1%E5%8A%A8%E6%89%8B%E4%B8%80%E6%89%B9%E9%87%8F%E7%A7%BB%E5%8A%A8%E9%87%8D%E5%91%BD%E5%90%8D%E6%96%87%E4%BB%B6/" class="title">自己动手（一）——批量移动、重命名文件</a>
                    </p>
                    <p class="item-date">
                        <time datetime="2020-07-27 17:50:02 &#43;0800 CST" itemprop="datePublished">2020-07-27</time>
                    </p>
                </div>
            </li>
            <li>
                <div class="item-inner">
                    <p class="item-title">
                        <a href="https://rulerLwx.gitee.io/2020/07/%E5%85%B3%E4%BA%8Einteger%E7%9A%84-128~127%E7%BC%93%E5%AD%98/" class="title">关于Integer的 -128~127缓存</a>
                    </p>
                    <p class="item-date">
                        <time datetime="2020-07-11 16:56:21 &#43;0800 CST" itemprop="datePublished">2020-07-11</time>
                    </p>
                </div>
            </li>
            <li>
                <div class="item-inner">
                    <p class="item-title">
                        <a href="https://rulerLwx.gitee.io/2020/07/%E8%B7%A8%E5%9F%9F%E9%97%AE%E9%A2%98/" class="title">跨域问题</a>
                    </p>
                    <p class="item-date">
                        <time datetime="2020-07-08 22:41:12 &#43;0800 CST" itemprop="datePublished">2020-07-08</time>
                    </p>
                </div>
            </li>
            <li>
                <div class="item-inner">
                    <p class="item-title">
                        <a href="https://rulerLwx.gitee.io/2020/07/%E4%B8%AA%E4%BA%BA%E5%8D%9A%E5%AE%A2%E6%90%AD%E5%BB%BA/" class="title">个人博客搭建</a>
                    </p>
                    <p class="item-date">
                        <time datetime="2020-07-05 18:58:47 &#43;0800 CST" itemprop="datePublished">2020-07-05</time>
                    </p>
                </div>
            </li>
            <li>
                <div class="item-inner">
                    <p class="item-title">
                        <a href="https://rulerLwx.gitee.io/2020/07/centos/" class="title">CentOS-</a>
                    </p>
                    <p class="item-date">
                        <time datetime="2020-07-01 18:58:47 &#43;0800 CST" itemprop="datePublished">2020-07-01</time>
                    </p>
                </div>
            </li>
        </ul>
    </div>
</div>
  </div>
</aside>

    
    
<aside class="sidebar sidebar-toc collapse" id="collapseToc" itemscope itemtype="http://schema.org/WPSideBar">
  <div class="slimContent">
    <h4 class="toc-title">Catalogue</h4>
    <nav id="toc" class="js-toc toc">

    </nav>
  </div>
</aside>
<main class="main" role="main"><div class="content">
  <article id="-" class="article article-type-" itemscope
    itemtype="http://schema.org/BlogPosting">
    
    <div class="article-header">
      <h1 itemprop="name">
  <a
    class="article-title"
    href="/2020/07/java-se-%E9%9B%86%E5%90%88/"
    >Java-Se-集合</a
  >
</h1>

      <div class="article-meta">
        
<span class="article-date">
  <i class="icon icon-calendar-check"></i>&nbsp;
<a href="https://rulerLwx.gitee.io/2020/07/java-se-%E9%9B%86%E5%90%88/" class="article-date">
  <time datetime="2020-07-01 18:58:47 &#43;0800 CST" itemprop="datePublished">2020-07-01</time>
</a>
</span>
<span class="article-category">
  <i class="icon icon-folder"></i>&nbsp;
  <a class="article-category-link" href="/categories/java-se/"> Java-Se </a>
</span>  
  <span class="article-tag">
    <i class="icon icon-tags"></i>&nbsp;
    <a class="article-tag-link" href="/tags//">  </a>
  </span>

        <span class="post-comment"><i class="icon icon-comment"></i>&nbsp;<a href="/2020/07/java-se-%E9%9B%86%E5%90%88/#comments"
            class="article-comment-link">Comments</a></span>
		<span class="post-wordcount hidden-xs" itemprop="wordCount">Word Count: 4943words</span>
		<span class="post-readcount hidden-xs" itemprop="timeRequired">Read Count: 10minutes </span>
      </div>
    </div>
    <div class="article-entry marked-body js-toc-content" itemprop="articleBody">
      <h1 id="collection">Collection</h1>
<h2 id="集合体系家族">集合体系、家族</h2>
<p>常用的集合类：</p>
<pre><code class="language-other">java.util.Collection
        |- Set
            |- HashSet
            |- LinkedHashSet
            |- TreeSet
            |- EnumSet
        |- List
            |- ArrayList
            |- LinkedList
            |- Vector
        |- Queue
            |- PriorityQueue
            |- Deque
                |- ArrayDeque
            |- LinkedList

java.util.Map
        |- HashMap
        |- Hashtable
        |- LinkedHashMap
        |- TreeMap
        |- EnumMap
        |- Properties

</code></pre>
<h2 id="关于迭代">关于迭代</h2>
<p>问：在迭代过程中能否增加、删除元素？</p>
<p>答：最好在迭代过程中不操作元素，将触发<code>java.util.ConcurrentModificationException</code>异常。如果真有此需求，有以下方案：</p>
<ul>
<li>使用Iterator遍历集合，使用<code>it.remove()</code>方法删除集合中的元素，删除的是上一次<code>next()</code>方法返回的元素；</li>
<li>使用“写时复制”代替原生的集合，如使用<code>CopyOnWriteArrayList</code>替换<code>ArrayList</code>，适合“读多写少”的情况</li>
</ul>
<p><code>java.util.ConcurrentModificationException</code>异常，示例：</p>
<pre><code class="language-java">    public static void main(String[] args) {
        HashSet&lt;String&gt; books = new HashSet&lt;&gt;();
        books.add(&quot;疯狂Java讲义&quot;);
        books.add(&quot;疯狂Androroid讲义&quot;);
        books.add(&quot;轻量级JavaEE企业应用实战&quot;);

        Iterator&lt;String&gt; it = books.iterator();
        while (it.hasNext()) {
            String book = it.next();
            if (&quot;疯狂Androroid讲义&quot;.equals(book)) {
                it.remove();// 此处的删除，不报错
                //books.remove(book);// 此处的删除，报错
            }
        }
    }
</code></pre>
<p>参考《疯狂JAVA讲义（第三版）》P286</p>
<h1 id="以前的笔记">以前的笔记</h1>
<pre><code class="language-t">set:无序、不重复
list:有序、可重复

set:
只要不重复就可以存，用的是equals()方法,而不是==
   |-- equals()返回true，hashCode()返回true,------&gt; 一定不存
   |--- equals()返回true，hashCode()返回false,------&gt; 可存（因为是通过hashCode值来计算存储的位置，所以hashCode值不同，存在不同的位置。）
实际开发中，尽量保证：equals()返回true时，hashCode()也返回true

treeSet：
    |---subSet(),headSet(),tailSet()这三个方法理解成：treeSet是按小--&gt;大（低--&gt;高）排（升序）
    |---添加到treeSet中的对象所对应的类必须实现Comparable接口，否则抛ClassCastException
    |---添加到treeSet听的对象应该属于同一个类，否则抛ClassCastException
    
    treeSet是根据红黑树来计算存储的位置
    treeSet判断对象的唯一标准是：compareTo(Object obj)返回的是否是0,是则不存。

集合中应存放不可变的对象作为key

EnumSet不可以插入null值


在所有的Set集合中：
1、EnumSet性能最好，但所有元素必须是指定枚举类型的枚举值
2、其次是HashSet,
3、treeSet、LinkedHashSet可以记住插入的顺序

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~List集合
    |-----判断对象是否相等的标准是：equals()返回true;
    |-----listIteretor比Iterator灵活，可以前后迭代；

ArrayList，是不线程安全的
Vactor，是线程安全的，
Stack，是Vector子类，性能更差，推荐用LinkedList\LinkedDeque

Arrays.asList(Object ....a)返回的是一个ArrayList,这个ArrayList，程序只能遍历，不能增、删该集合元素。
---------------------------------------------------------------------------------------------------------------------------------Queue集合
    |----PriorityQueue，不是按队列的“先进先出”的方式，而是按由小到大的顺序排序和输出。

队列用poll，栈用pop

双端队列（队列和栈），进行操作的时候，如果用到是队列的方法，就把它看成是队列；如果用的是栈的方法，就把它看成是栈。
（队列的头就是栈的栈顶，队列的尾就是栈的底）

---------------------------------------------------------------------------------------------------------------------------------Map集合
|-----所有的key组成的是Set集合，所以具有无序、不可重复特点。判断key相等的标准同Set，即equals()、hashCode().
|-----所有的value组成的是List集合，所以具有有序、可重复特点。

Hashtable：古老，线程安全，key、value不可以为null
HashMap：1.2开始，线程不安全，key、value可以为null

Hashtable、HashMap判断两个key是否相等的标准是：两个key通过equals()方法比较返回true时，两个key通过HashCode()方法返回也是true。（把key当作set集合来看，符合set的标准）

HashMap、Hashtable不保证插入的顺序，LinkedHashMap保持插入时的顺序。

Properties是Hashtable的子类。

SortedMap接口和TreeMap实现类：
TreeMap：红黑树，判断key相等的标准与TreeSet同：两个key通过compareTo()方法比较返回0，

WeakHashMap:弱引用

IdentityHashMap:当且仅当两个key严格相等（key1==key2）时，IdetityHashMap才认为这两个key相等。

EnumMap：key不可以为null,key必须是单个枚举类的枚举值。

总结
可以维护顺序的Map有：
LinkedHashMap保持插入时的顺序，
TreeMap有自然顺序、定制顺序，
EnumMap自然顺序，即枚举类中定义的顺序，
注：HashMap是无序的

Enumeration接口：jdk1.0开始，方法命名太长，建议用Iterator替代，

操作集合的工具类：Collections

=============================================================================
Map集合的containsKey()方法，要想bean中的某个实体是否相等，这个实体必须要重写hashCode()、equals()方法。

iterator it = xxx.iterator;
每次it.next(),这个”iterator表格“都会向下移动一行，即不能操作上一行数据了，甚至会抛NoSuchElementException异常。
</code></pre>
<h1 id="map">Map</h1>
<p>常用的Map有</p>
<ul>
<li>HashMap</li>
<li>LinkedHashSet</li>
<li>ConcurrentHashMap</li>
</ul>
<h2 id="hashmap">HashMap</h2>
<h3 id="存数据putk-key-v-value-">存数据<code>put(K key, V value) </code></h3>
<ul>
<li>以“数组+链表”结构实现存储。</li>
<li>以hash算法计算存储位置。</li>
<li>默认数组大小：<code>int DEFAULT_INITIAL_CAPACITY = 1 &lt;&lt; 4; // aka 16</code>，一定要是2的次方。</li>
<li>扩展数组策略：<code>resize(2 * table.length);</code></li>
<li>用Entry类来封装一个key-value对，其中next即是用链表方式保存另一个key-value对，也就是“通过hash相同，但equals()方法返回false”的键值对。</li>
</ul>
<p><img src="https://gitee.com/rulerLwx/PicGo/raw/master/img/20200707182216.png" alt=""></p>
<p>JDK8，当链表长度大于8时，链表就转换为红黑树，提高查询效率。</p>
<p><img src="https://gitee.com/rulerLwx/PicGo/raw/master/img/20200707182248.png" alt=""></p>
<h3 id="取数据getkey">取数据<code>get(key)</code></h3>
<p>步骤：</p>
<ul>
<li>获取key的hashcode，通过hash()算法获得hash值，进而定位到数组位置</li>
<li>如果有多个元素，在链表上挨个比较key对象，调用的是equals()方法</li>
</ul>
<p>Java中规定：两个equals()为true的对象必须具有相同的hashcode。</p>
<hr>
<p>HashMap之put、get源码：</p>
<pre><code class="language-java">    public V put(K key, V value) {
        if (table == EMPTY_TABLE) {
            inflateTable(threshold);
        }
        if (key == null)
            return putForNullKey(value);
        int hash = hash(key);
        int i = indexFor(hash, table.length);
        //下面的for循环的作用是：对于key，hash相同时，判断equals，注意这里的next，跟Entry中的next一致
        //也就是链表关联元素
        for (Entry&lt;K,V&gt; e = table[i]; e != null; e = e.next) {      
            Object k;
            if (e.hash == hash &amp;&amp; ((k = e.key) == key || key.equals(k))) {
                V oldValue = e.value;
                e.value = value;
                e.recordAccess(this);
                return oldValue;
            }
        }

        modCount++;
        addEntry(hash, key, value, i);
        return null;
    }

    public V get(Object key) {
        if (key == null)
            return getForNullKey();
        Entry&lt;K,V&gt; entry = getEntry(key);

        return null == entry ? null : entry.getValue();
    }
    final Entry&lt;K,V&gt; getEntry(Object key) {
        if (size == 0) {
            return null;
        }

        int hash = (key == null) ? 0 : hash(key);
        // 这个for循环作用：循环查找同一个key下的不同值
        for (Entry&lt;K,V&gt; e = table[indexFor(hash, table.length)];
             e != null;
             e = e.next) {
            Object k;
            if (e.hash == hash &amp;&amp;
                ((k = e.key) == key || (key != null &amp;&amp; key.equals(k))))
                return e;
        }
        return null;
    }

</code></pre>
<p>总结：关键是要理解Entry类中的next实例变量的作用——作链表结构用，才能理解key的hash相同而equal()返回false的存储情况。</p>
<h3 id="扩容">扩容</h3>
<p>HashMap初始大小是16，当数组中的元素达到 0.75*数组length 时，就重新调整数组大小为原来的2倍。</p>
<p>扩容的本质是重新定义更大的数组，将原来数组中的元素拷贝到新数据中。</p>
<p>问：HashMap扩容后，元素位置如何变化？</p>
<p>答：HashMap 扩容后，原来的元素，要么在原位置，要么在原位置+原数组长度 那个位置上。</p>
<p>参考：https://blog.csdn.net/wohaqiyi/article/details/81448176</p>
<h2 id="hashmap和concurrenthashmap区别">HashMap和ConcurrentHashMap区别</h2>
<p>Hashtable线程安全，但效率低</p>
<p>TODO&hellip;</p>
<h1 id="set">Set</h1>
<ul>
<li>
<p>HashSet</p>
<ol>
<li>内部是HashMap。</li>
<li>add(key)方法，其实是调用HashMap的put(key,new Object())，所有的value用一个Object对象代替。</li>
</ol>
</li>
</ul>
<h1 id="list">List</h1>
<ul>
<li>
<p>ArrayList</p>
<ul>
<li>以数组结构实现List.</li>
<li>默认的数组大小是10，<code>DEFAULT_CAPACITY = 10;</code>.</li>
<li>当数组装满了，扩展的策略：<code>int newCapacity = oldCapacity + (oldCapacity &gt;&gt; 1);</code>，也就是增加原来数组长度的一半，另外，如果增加的是集合，则需要另外判断扩展的大小，则按最后复制数组<code>elementData = Arrays.copyOf(elementData, newCapacity);</code></li>
</ul>
</li>
<li>
<p>LinkedList</p>
<ul>
<li>以链表结构实现List。</li>
<li>Node静态内部类，是实现链表的关键。</li>
</ul>
</li>
</ul>
<h1 id="faq">FAQ</h1>
<h2 id="56treemap和treeset在排序时如何比较元素collections工具类中的sort方法如何比较元素">56、TreeMap和TreeSet在排序时如何比较元素？Collections工具类中的sort()方法如何比较元素？</h2>
<p>答：TreeSet要求存放的对象所属的类必须实现Comparable接口，该接口提供了比较元素的compareTo()方法，当插入元素时会回调该方法比较元素的大小。TreeMap要求存放的键值对映射的键必须实现Comparable接口从而根据键对元素进行排序。Collections工具类的sort方法有两种重载的形式，第一种要求传入的待排序容器中存放的对象比较实现Comparable接口以实现元素的比较；第二种不强制性的要求容器中的元素必须可比较，但是要求传入第二个参数，参数是Comparator接口的子类型（需要重写compare方法实现元素的比较），相当于一个临时定义的排序规则，其实就是通过接口注入比较元素大小的算法，也是对回调模式的应用（Java中对函数式编程的支持）。</p>
<p>参考：http://blog.csdn.net/jackfrued/article/details/44921941</p>
<h2 id="javautilconcurrentmodificationexception">java.util.ConcurrentModificationException</h2>
<p>集合在add/set/remove时，都会使modCount++，for(XXX xx : Collection)循环内部使用的就是iterator进行遍历，调用next()方法时会判断modCount != expectedModCount时，就抛此异常。</p>
<p>总结：遍历集合过程中不能添加元素，但可以删除元素（使用iterator.remove）。</p>
<h2 id="一个arraylist在循环过程中删除会不会出问题为什么">一个ArrayList在循环过程中删除，会不会出问题，为什么。</h2>
<p>List 循环遍历中删除元素问题一：https://blog.csdn.net/weixin_36759405/article/details/82767430</p>
<p>List 循环遍历中删除元素问题二：https://blog.csdn.net/weixin_36759405/article/details/83904452</p>
<h2 id="hashmap底层为什么一定用数组">HashMap底层为什么一定用数组</h2>
<p>1）数组效率高</p>
<p>在HashMap中，定位桶的位置是利用元素的key的哈希值对数组长度取模得到。此时，我们已得到桶的位置。显然数组的查找效率比LinkedList大。</p>
<p>2）可自定义扩容机制</p>
<p>采用基本数组结构，扩容机制可以自己定义，HashMap中数组扩容刚好是2的次幂，在做取模运算的效率高。</p>
<p>（如：ArrayList底层也是数组，但是扩容机制是1.5倍扩容）</p>
<p><a href="https://www.cnblogs.com/MWCloud/p/11379775.html">https://www.cnblogs.com/MWCloud/p/11379775.html</a></p>

    </div>
    <div class="article-footer">
<blockquote class="mt-2x">
  <ul class="post-copyright list-unstyled">
    <li class="post-copyright-link hidden-xs">
      <strong>Permalink: </strong>
      <a href="https://rulerLwx.gitee.io/2020/07/java-se-%E9%9B%86%E5%90%88/" title="Java-Se-集合" target="_blank" rel="external">https://rulerLwx.gitee.io/2020/07/java-se-%E9%9B%86%E5%90%88/</a>
    </li>
    <li class="post-copyright-license">
      <strong>License：</strong><a href="http://creativecommons.org/licenses/by/4.0/deed.zh" target="_blank" rel="external">CC BY 4.0 CN</a>
    </li>
  </ul>
</blockquote>

<div class="panel panel-default panel-badger">
  <div class="panel-body">
    <figure class="media">
      <div class="media-left">
        <a href="https://gitee.com/rulerLwx" target="_blank" class="img-burn thumb-sm visible-lg">
          <img src="https://rulerLwx.gitee.io/avatar.png" class="img-rounded w-full" alt="">
        </a>
      </div>
      <div class="media-body">
        <h3 class="media-heading"><a href="https://gitee.com/rulerLwx" target="_blank"><span class="text-dark">rulerLwx</span><small class="ml-1x">thinking...</small></a></h3>
        <div>Good Good Study, Day Day Up~</div>
      </div>
    </figure>
  </div>
</div>
    </div>
  </article>
<section id="comments">
    <div id="vcomments"></div>
</section>

</div><nav class="bar bar-footer clearfix" data-stick-bottom>
    <div class="bar-inner">
        <ul class="pager pull-left">
            <li class="prev">
                <a href="https://rulerLwx.gitee.io/2020/07/java-se-%E9%9D%A2%E5%90%91%E5%AF%B9%E8%B1%A1/" title="Java-Se-面向对象"><i
                        class="icon icon-angle-left"
                        aria-hidden="true"></i><span>&nbsp;&nbsp;Older</span></a>
            </li>
            <li class="next">
                <a href="https://rulerLwx.gitee.io/2020/07/java-se-%E7%BD%91%E7%BB%9C%E7%BC%96%E7%A8%8B-2-%E6%8F%A1%E6%89%8B/"
                    title="Java-Se-网络编程-2"><span>Newer&nbsp;&nbsp;</span><i
                        class="icon icon-angle-right" aria-hidden="true"></i></a>
            </li>
            
            <li class="toggle-toc">
                <a class="toggle-btn collapsed" data-toggle="collapse" href="#collapseToc" aria-expanded="false"
                    title="Catalogue" role="button">
                    <span>[&nbsp;</span><span>Catalogue</span>
                    <i class="text-collapsed icon icon-anchor"></i>
                    <i class="text-in icon icon-close"></i>
                    <span>]</span>
                </a>
            </li>
        </ul>
        <div class="bar-right">
            <div class="share-component" data-sites="weibo,qq,wechat"
                data-mobile-sites="weibo,qq,qzone"></div>
        </div>
    </div>
</nav>

</main><footer class="footer" itemscope itemtype="http://schema.org/WPFooter">
<ul class="social-links">
    <li><a href="https://gitee.com/rulerLwx" target="_blank" title="gitee" data-toggle=tooltip data-placement=top >
            <i class="icon icon-gitee"></i></a></li>
    <li><a href="https://github.com/wolf-lea" target="_blank" title="github" data-toggle=tooltip data-placement=top >
            <i class="icon icon-github"></i></a></li>
</ul>
  <div class="copyright">
    &copy;2020  -
    2020
    <div class="publishby">
        Theme by <a href="https://github.com/xiaoheiAh" target="_blank"> xiaoheiAh </a>base on<a href="https://github.com/xiaoheiAh/hugo-theme-pure" target="_blank"> pure</a>.
    </div>
  </div>
</footer>

<script src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.2/MathJax.js?config=TeX-MML-AM_SVG"></script>
<script type="text/x-mathjax-config">
    MathJax.Hub.Config({
            showMathMenu: false, //disables context menu
            tex2jax: {
            inlineMath: [ ['$','$'], ['\\(','\\)'] ]
           }
    });
</script>


<script src="https://cdn.jsdelivr.net/npm/jquery@3.4.1/dist/jquery.min.js"></script>
<script>
    window.jQuery || document.write('<script src="js/jquery.min.js"><\/script>')
</script>
<script type="text/javascript" src="https://cdn.staticfile.org/highlight.js/9.15.10/highlight.min.js"></script>
<script type="text/javascript" src="https://cdn.staticfile.org/highlight.js/9.15.10/languages/python.min.js" defer></script>
<script type="text/javascript" src="https://cdn.staticfile.org/highlight.js/9.15.10/languages/javascript.min.js" defer></script><script>
    hljs.configure({
        tabReplace: '    ', 
        classPrefix: ''     
        
    })
    hljs.initHighlightingOnLoad();
</script>
<script src="https://rulerLwx.gitee.io/js/application.min.bdeb64b910570b6c41badc6a05b7afb0c8ad9efd8525de3c7257d59e786326a3.js"></script>
<script src="https://rulerLwx.gitee.io/js/plugin.min.51ff8c7317566f82259170fa36e09c4493adc9b9378b427a01ad3f017ebac7dd.js"></script>

<script>
    (function (window) {
        var INSIGHT_CONFIG = {
            TRANSLATION: {
                POSTS: 'Posts',
                PAGES: 'Pages',
                CATEGORIES: 'Categories',
                TAGS: 'Tags',
                UNTITLED: '(Untitled)',
            },
            ROOT_URL: 'https:\/\/rulerLwx.gitee.io',
            CONTENT_URL: 'https:\/\/rulerLwx.gitee.io\/searchindex.json ',
        };
        window.INSIGHT_CONFIG = INSIGHT_CONFIG;
    })(window);
</script>
<script type="text/javascript" src="https://rulerLwx.gitee.io/js/insight.min.a343cd9a5a7698336b28ef3a7c16a3a1b1d2d5fb17dc8ed04022bbe08cc5459073a15bdafa3a8a58cdd56080784bdd69fa70b1ae8597565c799c57ed00f0e120.js" defer></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/tocbot/4.4.2/tocbot.min.js"></script>
<script>
    tocbot.init({
        
        tocSelector: '.js-toc',
        
        contentSelector: '.js-toc-content',
        
        headingSelector: 'h1, h2, h3',
        
        hasInnerContainers: true,
    });
</script>

<script src="https://cdn1.lncld.net/static/js/3.0.4/av-min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/valine"></script>
<script type="text/javascript">
    var GUEST = ['nick', 'mail', 'link'];
    var meta = 'nick,mail';
    meta = meta.split(',').filter(function (item) {
        return GUEST.indexOf(item) > -1;
    });
    new Valine({
        el: '#vcomments',
        verify: null ,
        notify: null ,
        appId: 'IyAB0PSPRazTPDxitO1ddQ7O-gzGzoHsz',
        appKey: '5rBJTq4KidYF33eXwvRVhtEH',
        placeholder: 'enjoy~',
        avatar: 'mm',
        meta: meta,
        pageSize: '10' || 10,
        visitor: false 
});
</script>

  </body>
</html>
